package net.anzix.jhacks.flexclipse.builder;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;

import flex2.tools.oem.Logger;
import flex2.tools.oem.Message;

public class ConsoleLogger implements Logger {

	final IProject project;

	private final static Map<String, Integer> errorCodeMapping = new HashMap<String, Integer>();
	static {
		errorCodeMapping.put(Message.ERROR, IMarker.SEVERITY_ERROR);
		errorCodeMapping.put(Message.WARNING, IMarker.SEVERITY_WARNING);
		errorCodeMapping.put(Message.INFO, IMarker.SEVERITY_INFO);
	}

	public ConsoleLogger(IProject project) {
		super();
		this.project = project;
	}

	protected void mark(final IResource resource, final Message message) throws CoreException {
		IMarker marker = resource.createMarker(IMarker.PROBLEM);
		marker.setAttribute(IMarker.SEVERITY, getSeverity(message));
		marker.setAttribute(IMarker.LINE_NUMBER, message.getLine());
		marker.setAttribute(IMarker.CHAR_START, message.getColumn());
		marker.setAttribute(IMarker.MESSAGE, message.toString());
		marker.setAttribute(IMarker.LOCATION, message.getPath());
	}
	
	protected int getSeverity(final Message message) {
		final Integer severity = errorCodeMapping.get(message.getLevel());
		return severity == null ? -1 : severity;
	}
	
	protected IResource getResource(Message message) {
		final String msgFile = message.getPath();
		if(msgFile == null) {
			return project;
		}
		File projectDir = project.getLocation().toFile();
		ArrayList<File> reversePath = new ArrayList<File>();
		for(File seek = new File(msgFile); !projectDir.equals(seek); seek = seek.getParentFile()) {
			reversePath.add(seek);
		}
		IResource resource = project;
		for(int i = reversePath.size() - 1; i >= 0; i --) {
			if(resource instanceof IContainer) {
				resource = ((IContainer)resource).findMember(reversePath.get(i).getName());
			}
		}
		return resource;
	}
	
	public void log(final Message message, final int errorCode,
			final String source) {
		try {
			mark(getResource(message), message);
		} catch (CoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
